package com.sip.stream.helper;

import java.io.ByteArrayOutputStream;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Node;

public class DocumentHelper {
    private static final String TAG = "DocumentHelper";

    public String nodeToString(Node node) {
        try {
            Transformer newTransformer = TransformerFactory.newInstance().newTransformer();
            newTransformer.setOutputProperty("omit-xml-declaration", "yes");
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            newTransformer.transform(new DOMSource(node), new StreamResult(byteArrayOutputStream));
            return byteArrayOutputStream.toString();
        } catch (Exception unused) {
            return null;
        }
    }

    public String getStringValue(Document document, String nodeName) {
        for (int i = 0; i < document.getFirstChild().getChildNodes().getLength(); i++) {
            Node item = document.getFirstChild().getChildNodes().item(i);
            if (item.getNodeName().equalsIgnoreCase(nodeName) && item.getChildNodes().getLength() > 0) {
                return item.getFirstChild().getNodeValue();
            }
        }
        return null;
    }

    public Node getChildNode(Document document, String nodeName) {
        for (int i = 0; i < document.getFirstChild().getChildNodes().getLength(); i++) {
            Node item = document.getFirstChild().getChildNodes().item(i);
            if (item.getNodeName().equalsIgnoreCase(nodeName)) {
                return item;
            }
        }
        return null;
    }

    public Node getChildNode(Node node, String nodeName) {
        for (int i = 0; i < node.getChildNodes().getLength(); i++) {
            Node item = node.getChildNodes().item(i);
            if (item.getNodeName().equalsIgnoreCase(nodeName)) {
                return item;
            }
        }
        return null;
    }

    public String getStringValue(Node node, String nodeName) {
        for (int i = 0; i < node.getChildNodes().getLength(); i++) {
            Node item = node.getChildNodes().item(i);
            if (item.getNodeName().equalsIgnoreCase(nodeName)) {
                return item.getTextContent();
            }
        }
        return null;
    }
}
